<?php

namespace common\widgets\datepicker;

use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\web\View;

class DatePicker extends InputWidget{
    
    public $search = false;
    public $format = 1;   //默认简单模式的日期格式，如(2020-11-11)
    
    public function init()
    {
        parent::init();
        $this->options['onclick'] = $this->generateOnclickJs();
        Html::addCssClass($this->options, 'form-control');
        
    }
    
    public function run()
    {   
        $input = $this->hasModel()
        ? Html::activeTextInput($this->model, $this->attribute, $this->options)
        : Html::textInput($this->name, $this->value, $this->options);
        
        
        $phpformat = 'Y-m-d';
        if($this->format == DateType::FULL){
            $phpformat = 'Y-m-d H:i:s';
        }
        
        if($this->search == false){
            $input = preg_replace('/value="([\d\D]*?)"/e','"value=\"".date($phpformat,$1)."\""',$input);   //进行format
        }
        
        echo $input;
        
        DatePickerAsset::register($this->view);
    }
    
    //生成onclick的事件
    public function generateOnclickJs(){
        $url = '/'.\Yii::$app->controller->id.'/'.\Yii::$app->controller->action->id;
        
        $jsformat = 'yyyy-MM-dd';
        if($this->format == DateType::FULL){
            $jsformat = 'yyyy-MM-dd H:mm:ss';
        }
        
        
        $js = "WdatePicker({dateFmt:'{$jsformat}'})";
        if($this->search == true){
            $js = "WdatePicker({dateFmt:'{$jsformat}',onpicked: function() {window.location.href = '{$url}?'+$('#w0 input').serialize();},oncleared: function() {window.location.href = '{$url}?'+$('#w0 input').serialize();}})";
        }
        return $js;
    }

} 